﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace SampleResizebleItem.Services
{
    public class Service
    {
        private string _apiKeyFlickr = "INSERT API KEY FLICKR";

        System.Collections.ObjectModel.ObservableCollection<Models.ModelImages> _resultFlickr = new System.Collections.ObjectModel.ObservableCollection<Models.ModelImages>();

        public void LoadFlickr(Action<System.Collections.ObjectModel.ObservableCollection<Models.ModelImages>, Exception> callback, string url)
        {
            var asyncrequest = (HttpWebRequest)WebRequest.Create("http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=" + _apiKeyFlickr + "&text=jakarta&sort=relevance&per_page=80");
            asyncrequest.BeginGetResponse(asyncresult =>
            {
                try
                {
                    if (_resultFlickr.Count > 0)
                        _resultFlickr.Clear();

                    var responsestream = (HttpWebResponse)asyncrequest.EndGetResponse(asyncresult);
                    System.IO.Stream stream = responsestream.GetResponseStream();
                    var reader = new System.IO.StreamReader(stream);
                    string stringResult = reader.ReadToEnd();

                    var xml = XElement.Parse(stringResult);
                    var data = from var in xml.Descendants("photo")
                               select new Models.ModelImages()
                               {
                                   Title = (var.Attribute("title").Value).ToUpper(),
                                   Type = "Flickr",
                                   ImageLarge = "http://farm" + var.Attribute("farm").Value + ".static.flickr.com/" + var.Attribute("server").Value + "/" + var.Attribute("id").Value + "_" + var.Attribute("secret").Value + ".jpg",
                                   ImageUrl = "http://farm" + var.Attribute("farm").Value + ".static.flickr.com/" + var.Attribute("server").Value + "/" + var.Attribute("id").Value + "_" + var.Attribute("secret").Value + ".jpg"
                               };

                    foreach (var flickr in data)
                    {
                        _resultFlickr.Add(flickr);
                    }


                    callback(_resultFlickr, null);

                }
                catch (Exception ex)
                {
                    if (ex.Message == "No Data")
                        callback(null, ex);
                    else
                        callback(null, new Exception(ex.Message));
                }

            }, null);
        }
    }
}
